package com.iflytek.springboot_medicine.service.impl;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import com.iflytek.springboot_medicine.entity.ChatRequest;
import com.iflytek.springboot_medicine.entity.ChatResponse;
import com.iflytek.springboot_medicine.entity.Message;
import com.iflytek.springboot_medicine.service.DeepSeekService;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

@Service
public class DeepseekImpl implements DeepSeekService {
    private static String API_KEY;
    private static String API_URL;

    static {
        Properties properties = new Properties();
        try {
            InputStream inputStream = DeepseekImpl.class.getResourceAsStream("/config.properties");
            properties.load(inputStream);
            API_KEY = properties.getProperty("key");
            API_URL = properties.getProperty("url");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String ask(String question) {
        List<Message> messages = new ArrayList<>();
        messages.add(new Message("user", question));

        ChatRequest requestBody = new ChatRequest(
                "deepseek-chat",
                messages,
                0.7,
                1000
        );
        System.out.println("正在提交问题>>>");
        long startTime = System.currentTimeMillis();
        String response = sendRequest(requestBody.toString());
        long endTime = System.currentTimeMillis();
        System.out.println("思考用时 " + (endTime - startTime) + " ms");
        System.out.println("回答： " + response);
        return sendRequest(requestBody.toString());
    }

    @Override
    public String sendRequest(String question) {
        Gson gson = new Gson();
        List<Message> messages = new ArrayList<>();
        messages.add(new Message("user", question));
        ChatRequest requestBody = new ChatRequest(
                "deepseek-chat",
                messages,
                0.7,
                1000
        );
        String requestBodyJson = gson.toJson(requestBody);

        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(30, TimeUnit.SECONDS)
                .setConnectionRequestTimeout(30, TimeUnit.SECONDS)
                .setResponseTimeout(30, TimeUnit.SECONDS)
                .build();
        try (CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build()) {
            HttpPost request = new HttpPost(API_URL);
            request.setHeader("Content-Type", "application/json");
            request.setHeader("Authorization", "Bearer " + API_KEY);
            request.setEntity(new StringEntity(requestBodyJson, ContentType.APPLICATION_JSON));

            try (CloseableHttpResponse response = client.execute(request)) {
                if (response.getCode() == 200) {
                    String responseContent = EntityUtils.toString(response.getEntity());
                    System.out.println("Response content: " + responseContent);

                    try {
                        ChatResponse chatResponse = gson.fromJson(responseContent, ChatResponse.class);
                        return chatResponse.getChoices().get(0).getMessage().getContent();
                    } catch (JsonSyntaxException e) {
                        return "响应内容不是有效的JSON格式: " + responseContent;
                    }
                } else {
                    return "请求状态码: " + response.getCode() + ", 响应: " + EntityUtils.toString(response.getEntity());
                }
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "请求异常: " + e.getMessage();
        }
    }


}
